<?php

namespace app\controller;

use app\model\User;
use app\model\Tweet;
use core\Event;

class UserController extends BaseController
{
    public function register(): void
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';

            if (empty($username) || empty($password)) {
                $this->render('user/register', ['error' => '用户名和密码不能为空']);
                return;
            }
            if (User::findByUsername($username)) {
                $this->render('user/register', ['error' => '用户名已存在']);
                return;
            }

            $user = new User(['username' => $username]);
            $user->password = $password; // 使用设置器来哈希密码
            $user->save();

            Event::dispatch('user.registered', $username, $user->id);
            $this->redirect('/user/login');
        }
        $this->render('user/register');
    }

    public function login(): void
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $user = User::findByUsername($username);

            if ($user && password_verify($password, $user->hash)) {
                $userSessionData = ['id' => $user->id, 'username' => $user->username];
                $_SESSION['user'] = $userSessionData;

                Event::dispatch('user.loggedin', $userSessionData);
                $this->redirect('/');
            } else {
                $this->render('user/login', ['error' => '用户名或密码错误']);
            }
            return;
        }
        $this->render('user/login');
    }

    public function profile(string $username): void
    {
        $this->requireLogin();
        $profileUser = User::findByUsername($username);

        if (!$profileUser) {
            http_response_code(404);
            echo "User not found";
            return;
        }

        $allTweets = Tweet::all();
        $userTweets = array_filter($allTweets, function (Tweet $tweet) use ($profileUser) {
            return $tweet->user_id === $profileUser->id && $tweet->parent_id === null;
        });
        usort($userTweets, fn($a, $b) => $b->timestamp - $a->timestamp);

        $currentUserId = $this->getCurrentUserId();
        $isFollowing = in_array($profileUser->id, $_SESSION['follows'][$currentUserId] ?? []);

        $this->render('user/profile', [
            'profileUser' => $profileUser,
            'tweets' => $userTweets,
            'isFollowing' => $isFollowing,
            'isOwnProfile' => $currentUserId === $profileUser->id
        ]);
    }

    // ... logout, follow, unfollow 方法保持不变，因为它们直接操作 session ...
    // ... (在真实应用中，这些也应该通过模型或服务来处理) ...
    /**
     * 登出
     */
    public function logout(): void
    {
        unset($_SESSION['user']);
        session_destroy();
        $this->redirect('/');
    }

    /**
     * 关注一个用户
     * @param int $userIdToFollow
     */
    public function follow(int $userIdToFollow): void
    {
        $this->requireLogin();
        $currentUserId = $this->getCurrentUserId();

        if ($currentUserId !== $userIdToFollow) {
            $_SESSION['follows'][$currentUserId][] = $userIdToFollow;
            $_SESSION['follows'][$currentUserId] = array_unique($_SESSION['follows'][$currentUserId]);
        }

        $this->redirect($_SERVER['HTTP_REFERER'] ?? '/');
    }

    /**
     * 取消关注一个用户
     * @param int $userIdToUnfollow
     */
    public function unfollow(int $userIdToUnfollow): void
    {
        $this->requireLogin();
        $currentUserId = $this->getCurrentUserId();

        if (isset($_SESSION['follows'][$currentUserId])) {
            $_SESSION['follows'][$currentUserId] = array_diff(
                $_SESSION['follows'][$currentUserId],
                [$userIdToUnfollow]
            );
        }

        $this->redirect($_SERVER['HTTP_REFERER'] ?? '/');
    }
}
